package com.bigfish.crm.web;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bigfish.common.utils.CommonUtil;
import com.bigfish.common.utils.PageItem;
import com.bigfish.crm.dto.LevelRule;
import com.bigfish.crm.dto.search.RuleSerachVo;
import com.bigfish.crm.service.LevelRuleService;

@Controller
@RequestMapping("/rules")
public class RulesController {
	@Autowired
	private LevelRuleService levelRuleService;
	
	/**
	 * 展示现有的规则
	 * 
	 * @return
	 */
	@RequestMapping(value = "/rulesList")
	public ModelAndView memberList(PageItem page) {
		ModelAndView mv=new ModelAndView("rules/ruleList");
		List<LevelRule> list=levelRuleService.getLevelRuleList(page);
		//list.forEach(System.out::println); 会导致jett8 报错，但是没什么大问题
		mv.addObject("ruleList",list);
		return mv;
	}
	
	/**
	 * 查看规则详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/ruleDetails")
	public ModelAndView ruleDetails(int id) {
		ModelAndView mv=new ModelAndView("rules/levelRuleEdit");
		mv.addObject("levelRule", levelRuleService.getLevelRuleById(id));
		return mv;
	}
	@RequestMapping(value = "/refresh")
	@ResponseBody
	public String refresh() {
		levelRuleService.refreshRules();
		return "{\"status\":\"ok\"}";
	}
	
	@RequestMapping(value = "/createRule")
	public ModelAndView memberList(RuleSerachVo ruleSearchVo) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		StringBuffer content=new StringBuffer("import com.bigfish.crm.dto.Member;\r\n");
		content.append("rule \""+ruleSearchVo.getRuleName()+"\"\r\n");
		
		//设置汉字描述
		StringBuffer desc=new StringBuffer("当 Member 属性:");
		desc.append(ruleSearchVo.getWhenIf());
		desc.append("大于 ");
		desc.append(ruleSearchVo.getMinValue());
		desc.append("并且 小于 ");
		desc.append(ruleSearchVo.getMaxValue());
		//设置属性值
		if(!CommonUtil.objectIsNull(ruleSearchVo.getRuleGroup())){
			content.append("activation-group ");
			content.append("\""+ruleSearchVo.getRuleGroup()+"\"");
			content.append("\r\n");
		}
		content.append("when\r\n");
		
		if("latestOrderTime".equals(ruleSearchVo.getWhenIf())){
			content.append("member:Member(latestOrderTime.time<System.currentTimeMillis()-");
			content.append(ruleSearchVo.getMinValue()*24*3600*1000);
			content.append(",latestOrderTime.time>System.currentTimeMillis()-");
			content.append(ruleSearchVo.getMaxValue()*24*3600*1000);
			content.append(")\r\n");
		}else{
			content.append("member:Member(");
			content.append(ruleSearchVo.getWhenIf());
			content.append(">");
			content.append(ruleSearchVo.getMinValue());
			content.append(",");
			content.append(ruleSearchVo.getWhenIf());
			content.append("<");
			content.append(ruleSearchVo.getMaxValue());
			content.append(")\r\n");
		}
		content.append("then\r\n");
		for(int i=0;i<ruleSearchVo.getThenDo().length;i++){
			content.append("member.set");
			content.append(captureName(ruleSearchVo.getThenDo()[i]));
			content.append("(");
			Field filed=ruleSearchVo.getClass().getDeclaredField(ruleSearchVo.getThenDo()[i]+"Value");
			filed.setAccessible(true);
			if("points".equals(ruleSearchVo.getThenDo()[i])){
				content.append(filed.get(ruleSearchVo).toString().replaceAll("BuySumMoney", "member.getBuySumMoney()"));
			}else{
				content.append("\""+filed.get(ruleSearchVo)+"\"");
			}
			content.append(");\r\n");
			desc.append("设置 "+ruleSearchVo.getThenDo()[i]);
			desc.append("为 "+filed.get(ruleSearchVo)+";");
		}
		content.append("end\r\n");
		
		//System.out.println(content.toString());
		//System.out.println(desc.toString());
		LevelRule lr=new LevelRule();
		lr.setContent(content.toString());
		lr.setCreateTime(new Date());
		lr.setDes(desc.toString());
		lr.setName(ruleSearchVo.getRuleName());
		lr.setStatus((byte)1);
		levelRuleService.insertLevelRule(lr);
		ModelAndView mv=new ModelAndView("rules/ruleList");
		mv.addObject("ruleList",levelRuleService.getLevelRuleList(new PageItem()));
		return mv;
	}
	
	@RequestMapping(value = "/redictCreateRule")
	public String redictCreateRule(LevelRule rule) {
		return "rules/createRule";
	}
	
	public LevelRule getRule(){
		LevelRule rule=new LevelRule();
		rule.setCreateTime(new Date());
		rule.setDes("数据库规则");
		rule.setStatus((byte)1);
		rule.setContent(getContent());
		return rule;
	}
	public String getContent(){
		StringBuffer sb=new StringBuffer("pageckage rules \r\n");
		sb.append("import com.bigfish.crm.dto.Member;\r\n");
		sb.append("import java.util.Date;\r\n");
		sb.append("rule \"A\"\r\n");
		sb.append("");
		return sb.toString();
	}
	
	public List<LevelRule> getRules(){
		List<LevelRule> list=new ArrayList<>();
		LevelRule rule=new LevelRule();
		rule.setContent("");
		rule.setCreateTime(new Date());
		rule.setDes("这是一个测试规则");
		rule.setId(1);
		rule.setStatus((byte)1);
		list.add(rule);
		//
		LevelRule rule2=new LevelRule();
		rule2.setContent("这是第二个业务规则");
		rule2.setCreateTime(new Date());
		rule2.setDes("这是一个测试规则2");
		rule2.setId(1);
		rule2.setStatus((byte)0);
		list.add(rule2);
		return list;
	}
	  public static String captureName(String name) {
		   //     name = name.substring(0, 1).toUpperCase() + name.substring(1);
//		        return  name;
		        char[] cs=name.toCharArray();
		        cs[0]-=32;
		        return String.valueOf(cs);
		        
		    }
}
